const fs = require('fs')
const path = require('path')
const xlsx = require('node-xlsx');
const {
	mkdirsSync,
} = require('../utils')
const {
	getYearWeek,
	getTime,
	getDate,
} = require('../utils/dateUtils')

const _DBMySQL = require('../dbs/db-mysql')
const _mongoDB = require('../dbs/db-mongo')

const _WebDB = new _DBMySQL({
	host: "localhost",
	user: "root",
	port: 3306,
	password: "atmd@dd_2015",
	database: "web_crawler",
	charset: "utf8_general_ci"
})
const _webCrawlerMongo = new _mongoDB('mongodb://127.0.0.1:54188', 'web_crawler')

const titleId = ['url_source', 'list_id', 'list_name', 'tags', 'profile', 'itemid', 'itemname', 'artist', 'album', 'cp', 'exclusivity']
const titleName = ['来源', '歌单id', '标题', '标签', '简介', '歌曲ID', '歌曲名', '歌手名', '专辑名', '唱片公司', '付费方式']

async function run() {
	let source = process.argv[2] || 'all'
	let minItem = process.argv[3] || 5
	let sourceName = '全部'
	if (source == 'wy')
		sourceName = '网易'
	if (source == 'qq')
		sourceName = 'QQ'
	let date = new Date()
	let week = getYearWeek()
	let exp_task_id = `${week}_${source}_min_${minItem}`
	let filename = `${sourceName}歌单_${week}_min_${minItem}.xlsx`
	filename = encodeURIComponent(filename)
	let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
	let task = await expTaskCol.findOne({
		task_id: week,
	})
	if (!task || !task._id) {
		task = {
			task_id: week,
			week,
			date: getDate(),
			exp_list: {},
			create_time: getTime(),
			modify_time: getTime(),
		}
	}
	let expTask = {
		exp_task_id,
		week,
		filename,
		minItem,
		source,
		status: 0,
	}
	task.exp_list[exp_task_id] = expTask
	task.list = []
	for (let key in task.exp_list) {
		task.list.push(task.exp_list[key])
	}
	if (!task._id) {
		expTaskCol.insertOne(task)
	} else {
		expTaskCol.updateOne({
			_id: task._id,
		}, {
			$set: {
				list: task.list,
				exp_list: task.exp_list,
				modify_time: getTime(),
			}
		})
	}
	let excelDir = path.resolve(`../data/excel/${week}`)
	mkdirsSync(excelDir)
	let where = ` (SELECT list_id FROM match_songlist GROUP BY list_id HAVING COUNT(itemid) > ${minItem}) `
	where += source == 'all' ? '' : ` AND url_source = '${source}' `
	let SQL = 'SELECT url_source, list_id, list_name, tags, profile, itemid, itemname, artist, album, cp, exclusivity FROM match_songlist '
	SQL += ` WHERE list_id in ${where} AND status = 0`
	let docs = await _WebDB.select(SQL)
	let data = []
	data.push(titleName)
	for (let i = 0; i < docs.length; i++) {
		let songlist = docs[i]
		let d = []
		for (let j = 0; j < titleId.length; j++) {
			if (titleId[j] == 'url_source') {
				let source = songlist[titleId[j]]
				let sourceName = '全部'
				if (source == 'wy')
					sourceName = '网易'
				if (source == 'qq')
					sourceName = 'QQ'
				d.push(sourceName)
			} else {
				d.push(songlist[titleId[j]])
			}
		}
		data.push(d)
	}
	let excelBuff = xlsx.build([{
		name: `${sourceName}歌单`,
		data
	}])
	fs.writeFileSync(path.join(excelDir, filename), excelBuff)
	task = await expTaskCol.findOne({
		task_id: week,
	})
	task.exp_list[exp_task_id].status = 1
	task.list = []
	for (let key in task.exp_list) {
		task.list.push(task.exp_list[key])
	}
	expTaskCol.updateOne({
		_id: task._id,
	}, {
		$set: {
			exp_list: task.exp_list,
			list: task.list,
			modify_time: getTime(),
		}
	})

	// let last = await matchSonglistCol.find().sort({
	// 	week: -1,
	// }).limit(1).toArray()
}

run().then(r => {
	console.log('---r---', r)
	setTimeout(() => {
		process.exit(0)
	}, 60000)
}).catch(e => {
	console.log('---e---', e)
	setTimeout(() => {
		process.exit(1)
	}, 60000)
})